package com.yeyks.app.controller.websocket.c2b;

import cn.hutool.json.JSONUtil;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.pojo.WebSocketBaseReceivePojo;
import com.yeyks.common.pojo.WebSocketBaseSendPojo;
import com.yeyks.commonReference.service.hotel.HotelSearchC2bService;
import com.yeyks.hotel.param.GrabTheOrderServiceGetNowGrabTheOrderedHotelListParam;
import com.yeyks.hotel.param.GrabTheOrderServiceGrabTheOrderParam;
import com.yeyks.hotel.vo.GrabTheOrderServiceGrabTheOrderVo;
import com.yeyks.hotel.vo.HotelInfoHotelSearchVo;
import com.yeyks.search.pojo.param.search.HotelSearchC2bListParam;
import com.yeyks.search.pojo.vo.search.HotelInfoHotelUnionSearchVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * v3.4
 * c2b抢单websocket
 */
@Component
@ServerEndpoint(value = "/webSocket/{userId}")
@Slf4j
public class C2bGrabTheOrderWebSocket {

    /*
        格式:Map<用户id, Map<session id, session对象>>
     */
    private static Map<Integer, Map<String, Session>> clientMap = new ConcurrentHashMap<>();
    private static ApplicationContext applicationContext;
    private static HotelSearchC2bService hotelSearchC2bService;
    /**
     * 用户id
     */
    private Integer userId;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        C2bGrabTheOrderWebSocket.applicationContext = applicationContext;
        hotelSearchC2bService = applicationContext.getBean(HotelSearchC2bService.class);
    }

    /**
     * v3.4
     * 添加用户
     *
     * @param userId
     * @param session
     */
    public static void add(Integer userId, Session session) {
        synchronized (C2bGrabTheOrderWebSocket.class + ":" + userId) {
            Map<String, Session> stringSessionMap = clientMap.get(userId);
            if (null == stringSessionMap) {
                stringSessionMap = new ConcurrentHashMap<>();
                clientMap.put(userId, stringSessionMap);
            }
            stringSessionMap.put(session.getId(), session);
        }
    }

    /**
     * v3.4
     * 移除用户
     *
     * @param userId
     */
    static void remove(Integer userId, String sessionId) {
        try {
            clientMap.get(userId).remove(sessionId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * v3.4
     * 建立连接
     */
    @OnOpen
    public void onOpen(@PathParam("userId") Integer userId, Session session) {
        try {
            if (null != userId) {
                //log.info("现在连接的客户id：" + session.getId() + "用户id为：" + userId);
                this.userId = userId;
                if (Objects.isNull(userId)) {
                    throw new ServiceException("webSocket错误:用户id错误");
                }
                add(userId, session);
            }
        } catch (Exception e) {
            log.info("错误信息{}", e.getLocalizedMessage());
            remove(userId, session.getId());
        }

    }

    /**
     * v3.4
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("websocket和服务端连接断开" + error.getMessage());
    }

    /**
     * v3.4
     * 连接关闭
     */
    @OnClose
    public void onClose(Session session) {
        remove(userId, session.getId());
    }

    /**
     * v3.4
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            WebSocketBaseReceivePojo webSocketBasePojo = JSONUtil.toBean(message, WebSocketBaseReceivePojo.class);
            WebSocketBaseSendPojo webSocketBaseSendPojo = new WebSocketBaseSendPojo().setType(webSocketBasePojo.getType());
            HotelSearchC2bListParam hotelSearchC2bListParam;
            HotelInfoHotelUnionSearchVo hotelInfoHotelUnionSearchVo;
            switch (webSocketBasePojo.getType()) {
                //处理抢单逻辑 101
                case 101:
                    GrabTheOrderServiceGrabTheOrderParam grabTheOrderParam = JSONUtil.toBean(webSocketBasePojo.getDataStr(), GrabTheOrderServiceGrabTheOrderParam.class);
                    grabTheOrderParam.setUserId(this.userId);
                    GrabTheOrderServiceGrabTheOrderVo vo = hotelSearchC2bService.grabTheOrder(grabTheOrderParam);
                    //创建返回结果
                    webSocketBaseSendPojo.setTimestamp(grabTheOrderParam.getTimestamp()).setDataStr(JSONUtil.toJsonStr(vo));
                    //发送结果
                    session.getAsyncRemote().sendText(JSONUtil.toJsonStr(webSocketBaseSendPojo));
                    break;
                //获取已抢单的列表 102
                case 102:
                    hotelSearchC2bListParam = JSONUtil.toBean(webSocketBasePojo.getDataStr(), HotelSearchC2bListParam.class);
                    hotelSearchC2bListParam.setUserId(this.userId);
                    //获取抢单列表
                    hotelInfoHotelUnionSearchVo = hotelSearchC2bService.getGrabTheOrderedHotelList(hotelSearchC2bListParam);
                    //创建返回结果
                    webSocketBaseSendPojo.setTimestamp(hotelSearchC2bListParam.getTimestamp()).setDataStr(JSONUtil.toJsonStr(hotelInfoHotelUnionSearchVo));
                    //发送结果
                    session.getAsyncRemote().sendText(JSONUtil.toJsonStr(webSocketBaseSendPojo));
                    break;
//                //获取自动抢单的列表 103
//                case 103:
//                    hotelSearchC2bListParam = JSONUtil.toBean(webSocketBasePojo.getDataStr(), GrabTheOrderServiceGetNowGrabTheOrderedHotelListParam.class);
//                    hotelSearchC2bListParam.setUserId(this.userId);
//                    //获取抢单列表
//                    hotelInfoHotelUnionSearchVo = hotelSearchC2bService.getNowAutoGrabTheOrderedHotelListVo(hotelSearchC2bListParam);
//                    //创建返回结果
//                    webSocketBaseSendPojo.setTimestamp(hotelSearchC2bListParam.getTimestamp()).setDataStr(JSONUtil.toJsonStr(hotelInfoHotelUnionSearchVo));
//                    //发送结果
//                    session.getAsyncRemote().sendText(JSONUtil.toJsonStr(webSocketBaseSendPojo));
//                    break;
                default:
                    session.getAsyncRemote().sendText(JSONUtil.toJsonStr(webSocketBaseSendPojo));
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * v3.4
     * 给指定用户推消息
     *
     * @param message
     * @param toUserId
     */
    public void sendMessageToUser(Integer userId, String message) {
        Map<String, Session> stringSessionMap = clientMap.get(userId);
        if (Objects.nonNull(stringSessionMap)) {
            for (Session session : stringSessionMap.values()) {
                session.getAsyncRemote().sendText(message);
            }
        }
    }

}
